package model

import (
	"gin/common"
	Mysql "gin/database"
	"gorm.io/datatypes"
	"strings"
)

type Media struct {
	Id             uint64         `json:"id" gorm:"column:id"`
	Md5Name        string         `json:"md5_name" gorm:"column:md5_name"`
	Md5            string         `json:"md5" gorm:"column:md5"`
	RelativePath   string         `json:"relative_path" gorm:"column:relative_path"`
	Type           string         `json:"type" gorm:"column:type"`
	Status         string         `json:"status" gorm:"column:status"`
	Param          datatypes.JSON `json:"param" gorm:"column:param"`
	Uuid           string         `json:"uuid" gorm:"column:uuid"`
	TaskUUID       string         `json:"task_uuid" gorm:"column:task_uuid"`
	TaskResultFile string         `json:"task_result_file" gorm:"column:task_result_file"`
}

// 设置表名
func (Media) TableName() string {
	return "media"
}

// 获取指定文件MD5数据
func (this *Media) GetMediaDataByMD5(MD5 string) (mediaData Media, err error) {

	result := Mysql.DB.Where("md5 = ?", MD5).First(&this)

	if this.Id == 0 {
		err = result.Error
	} else {
		mediaData = *this
	}

	return
}

// 插入媒体数据
func (this *Media) Insert() (id uint64, err error) {
	result := Mysql.DB.Create(&this)
	id = this.Id
	if result.Error != nil {
		err = result.Error
		return
	}
	return
}

// 更新文件状态通过 Md5Name
func (this *Media) UpdateStatusByMd5Name(Md5Name string, Status string) (err error) {
	result := Mysql.DB.Model(&this).
		Where("md5_name = ?", Md5Name).
		Update("status", Status)

	if result.Error != nil {
		err = result.Error
	}
	return
}

// 通过Md5 Name 查找媒体
func (this *Media) SelectMediaByMd5Name(Md5Name []string) (mediaData []Media, err error) {

	result := Mysql.DB.Where("md5_name in (?)", Md5Name).Find(&mediaData)

	if result.Error != nil {
		err = result.Error
	}

	return
}

// 通过Md5 Name 查找媒体
func (this *Media) FindMediaByMd5Name(Md5Name string) (mediaData Media, err error) {

	result := Mysql.DB.Where("md5 = ?", Md5Name).Take(&mediaData)

	if result.Error != nil {
		err = result.Error
	}

	return
}

// 通过Md5 Name 删除媒体
func (this *Media) RemoveMediaByMd5Name(Md5Name []string) (err error) {
	result := Mysql.DB.Where("md5_name in (?)", Md5Name).Delete(&this)

	if result.Error != nil {
		err = result.Error
	}
	return
}

func (this *Media) Find(Param common.Filter) (resData Media, err error) {

	dictOne := new(Media)
	db := Mysql.DB

	// 组装过滤条件
	if Param.Filter != nil {
		for key, val := range Param.Filter {
			vals := val.(map[string]interface{})
			if strings.Contains(key, "bw_") {
				db = db.Where(vals["condition"], vals["val1"], vals["val2"])
			} else {
				db = db.Where(vals["condition"], vals["val"])
			}
		}
	} else {
		db = db.Where("?", "1=1")
	}

	result := db.First(&dictOne)
	if result.Error != nil {
		err = result.Error
	}

	return *dictOne, err
}
